package org.remixlab.gnutopic.pojo;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXHandler extends DefaultHandler{
	
	private boolean inMessageId = false;
	private ArrayList<String> messageIdList = new ArrayList<String>();
	private String sTemp = null;

	public boolean isInMessageId() {
		return inMessageId;
	}

	public void setInMessageId(boolean inMessageId) {
		this.inMessageId = inMessageId;
	}

	public ArrayList<String> getMessageIdList() {
		return messageIdList;
	}

	public void setMessageIdList(ArrayList<String> messageIdList) {
		this.messageIdList = messageIdList;
	}

	//------ metodos de DefaultHandler..........
	
	public void characters(char[] ch, int start, int length) throws SAXException {
		String s = "";
		
		if(inMessageId){
			//leo los mensajes...
			if(length<36){
				//el id muy probablemente viene cortado, debo guardarlo temporalmente y luego concatenarlo
				if(sTemp!=null){
					s = sTemp + new String(ch, start, length);
					sTemp=null;
				}else{
					//guardo una parte de la cadena,
					sTemp = new String(ch, start, length);
				}
			}else{
				//aqui obtengo el id.
				s = new String(ch, start, length);	
			}
			
			//si s es diferente de vacio, entonces lo agrego a la lista.
			if(!s.equalsIgnoreCase("")){
				messageIdList.add(s);	
			}
			
		}
	}

	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		
	}

	public void endElement(String uri, String localName, String name) throws SAXException {
		// TODO Auto-generated method stub
		if(name.equalsIgnoreCase("messageid")){
			inMessageId = false;	
		}
		
	}

	public void endPrefixMapping(String prefix) throws SAXException {
		// TODO Auto-generated method stub
		
	}

	public void ignorableWhitespace(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		
	}

	public void processingInstruction(String target, String data)
			throws SAXException {
		// TODO Auto-generated method stub
		
	}

	public void setDocumentLocator(Locator locator) {
		// TODO Auto-generated method stub
		
	}

	public void skippedEntity(String name) throws SAXException {
		// TODO Auto-generated method stub
		
	}

	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
	}

	public void startElement(String uri, String localName, String name,
			Attributes atts) throws SAXException {
		
		// TODO Auto-generated method stub
		
		if(name.equalsIgnoreCase("messageid")){
			//si la etiqueta es messageid, entonces
			inMessageId = true;	
		}
		
	}

	public void startPrefixMapping(String prefix, String uri)
			throws SAXException {
		// TODO Auto-generated method stub
		
	}

	
	
}
